In [68]:
%matplotlib inline
import matplotlib
matplotlib.rcParams['image.interpolation'] = 'nearest'
import numpy as np
import matplotlib.pyplot as plt
from skimage import exposure, filters, io , color, feature
In [2]:
ic = io.ImageCollection('FINAL_TRAINING_DATA_SET/*.jpg')
In [69]:
matplotlib.rcParams['image.cmap'] = 'viridis'
matplotlib.rcParams['figure.figsize'] = (10, 7)
In [10]:
for i, image in enumerate(ic):
    im = color.rgb2gray(image)

    corner_img = feature.corner_harris(im)
    coords = feature.corner_peaks(corner_img)
    fig, axes = plt.subplots(1,2)
    axes[0].imshow(im, cmap='gray')
    axes[0].plot(coords[:, 1], coords[:, 0], 'o')
    axes[1].imshow(im, cmap='gray')
C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py:537: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  max_open_warning, RuntimeWarning)
In [ ]:
import scipy.ndimage as ndi
In [ ]:
ic = io.ImageCollection('Segmenting_image_data_set/*.jpg')
In [23]:
for i, image in enumerate(ic):
    #im = color.rgb2gray(image)
    im = image
    
    fig, axes = plt.subplots(1,2)
    
    # Filter to get rid of speckles
    img_med = ndi.median_filter(im, size=5)
    axes[0].imshow(img_med, cmap=plt.cm.gray, interpolation='nearest')
    axes[1].hist(img_med.flatten(), bins=40, range=(0, 150)) ## Plotting Histogram
    #axes[2].imshow( img_med <= 10 , cmap=plt.cm.gray)
C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py:537: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  max_open_warning, RuntimeWarning)

Canny edge detector¶

The Canny edge detector combines the Sobel filter with a few other steps to give a binary edge image. The steps are as follows:

  • Gaussian filter
  • Sobel filter
  • Non-maximal suppression
  • Hysteresis thresholding
In [73]:
from IPython.html import widgets
from skimage import data
from skimage import feature

def canny_demo(image, **kwargs):
    edges = feature.canny(image, **kwargs, sigma = 3)
    plt.imshow(edges)
    plt.show()
In [74]:
for i, image in enumerate(ic):
    im = color.rgb2gray(image)
    widgets.interact(canny_demo(im))
In [27]:
from sklearn.ensemble import RandomForestClassifier
from skimage import filters
from skimage import img_as_float

def _compute_features(im):
    gabor_frequencies = np.logspace(-3, 1, num=5, base=2)
    thetas = [0, np.pi/2]
    nb_fq = len(gabor_frequencies) * len(thetas)
    im = np.atleast_3d(im)
    im_gabor = np.empty((im.shape[-1], nb_fq) + im.shape[:2])
    for ch in range(im.shape[-1]):
        img = img_as_float(im[..., ch])
        for i_fq, fq in enumerate(gabor_frequencies):
            for i_th, theta in enumerate(thetas):
                tmp = filters.gabor(img, fq, theta=theta)
                im_gabor[ch, len(thetas) * i_fq + i_th] = \
                                    np.abs(tmp[0] + 1j * tmp[1])
    return im_gabor


def trainable_segmentation(im, mask):
    """
    Parameters
    ----------
    
    im : ndarray
        2-D image (grayscale or RGB) to be segmented
        
    mask : ndarray of ints
        Array of labels. Non-zero labels are known regions that are used
        to train the classification algorithm.
    """
    # Define features
    im_gabor = _compute_features(im)     
    nb_ch, nb_fq, sh_1, sh2 = im_gabor.shape
    # Training data correspond to pixels labeled in mask
    training_data = im_gabor[:, :, mask>0]
    training_data = training_data.reshape((nb_ch * nb_fq,
                                         (mask>0).sum())).T
    training_labels = mask[mask>0].ravel()
    # Data are from the remaining pixels
    data = im_gabor[:, :, mask == 0].reshape((nb_ch * nb_fq,
                                              (mask == 0).sum())).T
    # classification
    clf = RandomForestClassifier()
    clf.fit(training_data, training_labels)
    labels = clf.predict(data)
    result = np.copy(mask)
    result[mask == 0] = labels
    return result
In [28]:
beach = io.imread('Bells-Beach.jpg')
In [65]:
beach.shape[:-1]
Out[65]:
(960, 1280)
In [45]:
# Define mask of user-labeled pixels, which will be used for training
mask = np.zeros(beach.shape[:-1], dtype=np.uint8)
mask[700:] = 1
mask[:550, :650] = 2
mask[400:450, 1000:1100] = 3
plt.imshow(beach)
plt.contour(mask, colors='y')
Out[45]:
<matplotlib.contour.QuadContourSet at 0x22d85499a20>
In [46]:
mask
Out[46]:
array([[2, 2, 2, ..., 0, 0, 0],
       [2, 2, 2, ..., 0, 0, 0],
       [2, 2, 2, ..., 0, 0, 0],
       ...,
       [1, 1, 1, ..., 1, 1, 1],
       [1, 1, 1, ..., 1, 1, 1],
       [1, 1, 1, ..., 1, 1, 1]], dtype=uint8)
In [30]:
result = trainable_segmentation(beach, mask)
plt.imshow(color.label2rgb(result, beach, kind='mean'))
Out[30]:
<matplotlib.image.AxesImage at 0x22dc43293c8>
In [31]:
brain_cancer = io.imread('brain_cancer.jpg')
In [67]:
brain_cancer = brain_cancer.reshape(512,512)
brain_cancer.shape[:-1]
Out[67]:
(512,)
In [ ]: